<template>
	<view class="content1">
		<view v-if="showMenu" class="masking-layer" @click="showMenu=false"></view>
		<view v-if="showExpandMenu" class="masking-layer" @click="showExpandMenu=false"></view>
		<!-- 搜索和筛选区域 -->
		<view class="search-bar">
			<uni-search-bar v-model="searchKeyword" placeholder="菜品名称或桌号" @confirm="handleSearch" @clear="handleSearchClear"
				cancelButton="none" style="flex: 1;" />
			<view class="job-container">
				<text class="job">{{ job }}： {{name}}</text>
				<image src="/static/setup.svg" class="arrow" @click="toggleMenu" />
				<view v-if="showMenu" class="dropdown-menu">
					<view class="menu-item top" @click="handleChangePassword">修改密码</view>
					<view class="menu-item" @click="handleLogout">退出登录</view>
				</view>
			</view>
		</view>
		<scroll-view class="scroll" scroll-y refresher-enabled :refresher-triggered="isRefreshing"
			@refresherrefresh="onRefresherRefresh" @refresherrestore="onRefresherRestore">
			<DishItem v-for="(dish, index) in list" :getListData="getListData" :key="dish._id" :dish="dish" :index="index" />
			<!-- 			<DishListItem :list="list" :getListData="getListData" class="list"></DishListItem> -->
		</scroll-view>
		<view v-if="job==='服务员'||job==='管理员'||job==='收银员'" class="expand-menu">
			<image v-if="showExpandMenu" src="/static/go-order-white.svg" @click="handleGoOrder"></image>
			<image v-if="showExpandMenu" src="/static/change-place.svg" @click="handleChangePlace"></image>
			<image v-if="showExpandMenu" src="/static/clean.svg" @click="handleCleanPlace"></image>
			<image @click="showExpandMenu=!showExpandMenu" :src="showExpandMenu?'/static/more.svg':'/static/more-v.svg'">
			</image>
		</view>
		<!-- 修改密码弹出层 -->
		<uni-popup ref="popup" type="center">
			<view v-if="popupTitle==='修改密码'" class="popup-content">
				<view class="popup-title">{{popupTitle}}</view>
				<view class="form-item">
					<text>旧密码</text>
					<input v-model="oldPassword" type="password" class="password-input" :class="{'active':isFocus[1]}"
						@focus="isFocus[1]=true" @blur="isFocus[1]=false" placeholder="请输入旧密码" />
				</view>
				<view class="form-item">
					<text>新密码</text>
					<input v-model="newPassword" type="password" class="password-input" :class="{'active':isFocus[2]}"
						@focus="isFocus[2]=true" @blur="isFocus[2]=false" placeholder="请输入新密码" />
				</view>
				<view class="form-item">
					<text>确认新密码</text>
					<input v-model="confirmPassword" type="password" class="password-input" :class="{'active':isFocus[3]}"
						@focus="isFocus[3]=true" @blur="isFocus[3]=false" placeholder="请再次输入新密码" />
				</view>
				<view class="popup-buttons">
					<button class="btn-cancel" @click="closePopup">取消</button>
					<button class="btn-confirm" @click="submit">确认</button>
				</view>
			</view>
			<view v-if="popupTitle==='代客下单'" class="popup-content">
				<view class="popup-title">{{popupTitle}}</view>
				<view class="selectedPlace-form form-item">
					<text>请输入要点餐的桌号：</text>
					<input v-model.number="place" type="number" />
				</view>
				<view class="selectedPlace">
					<text v-for="item in 14" :key="item" :class="{'active':place===item}" @click="place=item">{{item}}</text>
				</view>
				<view class="popup-buttons">
					<button class="btn-cancel" @click="closePopup">取消</button>
					<button class="btn-confirm" @click="submit">确认</button>
				</view>
			</view>
			<view v-if="popupTitle==='清台'" class="popup-content">
				<view class="popup-title">{{popupTitle}}</view>
				<view class="selectedPlace-form form-item">
					<text>请输入要清台的桌号：</text>
					<input v-model.number="place" type="number" />
				</view>
				<view class="selectedPlace">
					<text v-for="item in turnoverList" :key="item.id" :class="{'active':place===item.place}"
						@click="place=item.place" :style="{backgroundColor:item.status===1?'#b5c4b1':'#eee'}">{{item.place}}</text>
				</view>
				<view class="popup-buttons">
					<button class="btn-cancel" @click="closePopup">取消</button>
					<button class="btn-confirm" @click="submit">确认</button>
				</view>
			</view>
			<view v-if="popupTitle==='换桌'" class="popup-content">
				<view class="popup-title">{{popupTitle}}</view>
				<view class="selectedPlace-form">
					<text>从：</text>
					<input v-model.number="place" type="number" />
					<text style="margin-left: 15rpx;"> 号桌</text>
				</view>
				<view class="selectedPlace">
					<text v-for="item in turnoverList" :key="item.id" :class="{'active':place===item.place}"
						@click="place=item.place">{{item.place}}</text>
				</view>
				<view class="selectedPlace-form">
					<text>到：</text>
					<input v-model.number="toPlace" type="number" />
					<text style="margin-left: 15rpx;"> 号桌</text>
				</view>
				<view class="selectedPlace">
					<text v-for="item in toPlaceList" :key="item" :class="{'active':toPlace===item}"
						@click="toPlace=item">{{item}}</text>
				</view>
				<view class=" popup-buttons">
					<button class="btn-cancel" @click="closePopup">取消</button>
					<button class="btn-confirm" @click="submit">确认</button>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script setup>
	import {
		ref,
		onMounted
	} from 'vue';
	import {
		onLoad,
		onShow
	} from "@dcloudio/uni-app";
	import {
		getAdminOrderDetailListByStatusApi,
		// getAdminOrderListStatusApi,
		getAdminTurnoverDoingListApi,
		putAdminTurnoverUpdateApi,
		putAdminTurnoverChangePlaceApi
	} from '../../api/admin';
	// import DishListItem from '../../components/DishListItem.vue';
	import DishItem from '../../components/DishItem.vue';
	import {
		callCloudFun
	} from '../../utiles/callCloudFun';

	const list = ref([]);
	const job = ref('');
	const name = ref('');
	const searchKeyword = ref('')
	const isRefreshing = ref(false);
	const showMenu = ref(false); // 控制下拉菜单的显示与隐藏
	const showExpandMenu = ref(false)
	const popup = ref(null); // uni-popup 实例
	const oldPassword = ref(''); // 旧密码
	const newPassword = ref(''); // 新密码
	const confirmPassword = ref(''); // 确认新密码
	const popupTitle = ref('')
	const place = ref(0)
	const toPlace = ref(0)
	const turnoverList = ref([])
	const toPlaceList = ref([])
	const isFocus = ref([false, false, false])

	onLoad((data) => {
		job.value = data.job;
		name.value = data.name;
	});

	onMounted(() => {
		if (!job.value) {
			console.log('job没有值');
			const userInfo = uni.getStorageSync("userInfo") || {};
			if (userInfo.job) {
				job.value = userInfo.job;
				name.value = userInfo.name;
				getListData();
			} else {
				uni.navigateTo({
					url: '/pages/employeeLogin/employeeLogin'
				});
			}
		}
		uni.setNavigationBarTitle({
			title: "员工操作-" + job.value
		})

	});

	onShow(() => {
		if (job.value && name.value) {
			getListData()
		} else {
			wx.reLaunch({
				url: 'pages/index/index'
			})
		}
	})

	const getListData = async () => {
		list.value = await getAdminOrderDetailListByStatusApi({
			job: job.value,
			keyword: searchKeyword.value.trim()
		})
		console.log('获取数据：', list.value);
	};

	const handleSearchClear = () => {
		searchKeyword.value = ''
		getListData()
	}

	const handleSearch = () => {
		getListData()
	}

	const onRefresherRefresh = async () => {
		isRefreshing.value = true;
		console.log('下拉刷新');
		await getListData(); // 重新获取数据
		isRefreshing.value = false; // 停止刷新动画
	};

	const onRefresherRestore = () => {
		console.log('刷新恢复');
	};

	// 切换下拉菜单的显示与隐藏
	const toggleMenu = () => {
		showMenu.value = !showMenu.value;
	};

	// 处理修改密码
	const handleChangePassword = () => {
		popupTitle.value = '修改密码'
		showMenu.value = false; // 关闭下拉菜单
		popup.value.open(); // 打开弹出层
	};

	const handleGoOrder = () => {
		place.value = 0
		popupTitle.value = '代客下单'
		showExpandMenu.value = false
		popup.value.open()
	}

	const handleCleanPlace = async () => {
		place.value = 0
		popupTitle.value = '清台'
		showExpandMenu.value = false
		// todo 获取数据
		turnoverList.value = await getAdminTurnoverDoingListApi()
		if (!turnoverList.value || turnoverList.value.length === 0) {
			uni.showModal({
				content: '当前没有餐桌需要清台',
				showCancel: false
			})
			return
		}
		popup.value.open()
	}

	const handleChangePlace = async () => {
		place.value = 0
		toPlace.value = 0
		toPlaceList.value = []
		popupTitle.value = '换桌'
		showExpandMenu.value = false
		turnoverList.value = await getAdminTurnoverDoingListApi()
		if (!turnoverList.value || turnoverList.value.length === 0) {
			await uni.showModal({
				content: '当前没有已下单的餐桌，不需要处理，直接换桌即可',
				showCancel: false
			})
			return
		}

		// 准备目的桌待选列表
		let i = 1
		while (true) {
			const hasPlace = turnoverList.value.some(item => i === item.place)
			if (!hasPlace) {
				toPlaceList.value.push(i)
				if (toPlaceList.value.length >= 14) {
					break
				}
			}
			i++
		}

		popup.value.open()
	}

	// 关闭弹出层
	const closePopup = () => {
		popup.value.close(); // 关闭弹出层
		resetForm(); // 重置表单
	};

	// 提交修改密码
	const submit = async () => {
		if (popupTitle.value === '修改密码') {
			if (!oldPassword.value || !newPassword.value || !confirmPassword.value) {
				uni.showToast({
					title: '请填写完整信息',
					icon: 'none'
				});
				return;
			}

			if (oldPassword.value.length < 6 || newPassword.value.length < 6) {
				wx.showToast({
					title: '密码长度不能小于6位',
					icon: 'none'
				})
				return
			}

			if (newPassword.value !== confirmPassword.value) {
				uni.showToast({
					title: '两次输入的新密码不一致',
					icon: 'none'
				});
				return;
			}

			if (oldPassword.value === newPassword.value) {
				uni.showToast({
					title: '新密码和旧密码相同',
					icon: 'none'
				})
				return
			}

			const userInfo = wx.getStorageSync('userInfo') || {}

			callCloudFun('employee', {
				id: userInfo.empId,
				oldPassword: oldPassword.value,
				newPassword: newPassword.value
			}).then(res => {
				uni.showToast({
					title: '修改成功'
				});
				closePopup()
			})

		} else if (popupTitle.value === '代客下单') {
			if (!place.value) {
				uni.showToast({
					title: '输入不正确，请重新输入',
					icon: 'error'
				})
				return
			}

			await uni.navigateTo({
				url: '/pages/user/user?place=' + place.value + '&job=' + job.value
			})
			closePopup()

		} else if (popupTitle.value === '换桌') {
			if (!place.value || !toPlace.value) {
				uni.showToast({
					title: '两个桌号必须填写完整',
					icon: 'none'
				})
				return
			}
			if (place.value === toPlace.value) {
				wx.showToast({
					title: '两个桌号不能是同一桌',
					icon: 'none'
				})
				return
			}

			let content = ''
			const turnover = turnoverList.value.find(item => item.place === place.value)
			if (!turnover) {
				content = `源桌 ${place.value} 号桌没有订单，不用处理`
			}

			const hasToPlace = turnoverList.value.some(item => item.place === toPlace.value)
			console.log("toPlace:", toPlace.value, hasToPlace);

			if (hasToPlace) {
				content = content + `${content ? '\n' : ''} 目的桌 ${toPlace.value} 号桌正在使用，等买单后再试`
			}

			if (content) {
				uni.showModal({
					title: '提示',
					content,
					confirmText: '知道了',
					showCancel: false
				})
				return
			}

			const res = await uni.showModal({
				title: '提示',
				content: `你确定要把 ${place.value} 号桌换到 ${toPlace.value} 号桌吗？`
			})

			if (res.cancel) {
				return
			}

			await putAdminTurnoverChangePlaceApi({
				turnoverId: turnover._id,
				fromPlace: place.value,
				toPlace: toPlace.value
			})
			getListData()

			popup.value.close()
			await uni.showModal({
				title: '提示',
				content: `换桌完成，${place.value} 号桌未完成的订单以后将送往 ${toPlace.value} 号桌`,
				showCancel: false,
				confirmText: '知道了'
			})
			resetForm()

		} else if (popupTitle.value === '清台') {
			if (!place.value) {
				uni.showToast({
					title: '请先输入桌号',
					icon: 'none'
				})
				return
			}
			const turnover = turnoverList.value.find(item => item.place === place.value)
			if (!turnover) {
				uni.showToast({
					title: '桌号不正确，或者该桌没有使用，不需要清台',
					icon: 'none'
				})
				return
			}

			const res = await uni.showModal({
				title: '提示',
				content: `你确定${turnover.place} 号桌客人已离开，需要清台吗？`
			})

			if (res.cancel) {
				return
			}

			await putAdminTurnoverUpdateApi({
				id: turnover._id,
				place: turnover.place,
				status: 2
			})

			popup.value.close(); // 关闭弹出层
			uni.showModal({
				content: `${turnover.place} 号桌清台成功`,
				showCancel: false,
				confirmText: '知道了'
			})
			resetForm(); // 重置表单
		}
	};

	// 重置表单
	const resetForm = () => {
		oldPassword.value = '';
		newPassword.value = '';
		confirmPassword.value = '';
		popupTitle.value = ''
		place.value = 0
		toPlace.value = 0
		toPlaceList.value = []

	};

	// 处理退出登录
	const handleLogout = () => {
		uni.removeStorageSync('userInfo');
		uni.removeStorageSync('loginData')
		uni.reLaunch({
			url: '/pages/index/index'
		});
	};
</script>

<style lang="scss" scoped>
	$primary-color: #ff5a5f;
	$secondary-color: #f4e2d8;
	$font-size-base: 32rpx;
	$spacing-base: 20px;

	@mixin fixed-position($z-index) {
		position: fixed;
		z-index: $z-index;
	}

	.content1 {
		padding-top: 155rpx;
		background-color: #fff;
		height: 100vh;
		box-sizing: border-box;
		padding-bottom: env(safe-area-inset-bottom);
		overflow: hidden;

		.masking-layer {
			@include fixed-position(9);
			top: 0;
			left: 0;
			width: 100vw;
			height: 100vh;
			background: rgba(0, 0, 0, 0.2);
		}

		.search-bar {
			display: flex;
			align-items: center;
			padding: 20rpx 30rpx 20rpx 20rpx;
			background-color: #ffffff;
			border-bottom: 1rpx solid #ddd;
			box-sizing: border-box;
			width: 100%;
			height: 150rpx;
			position: fixed;
			top: 0;
			left: 0;
			z-index: 10;

			::v-deep .uni-searchbar__placeholder {
				white-space: nowrap;
				overflow: hidden;
				text-overflow: ellipsis;
			}

			.job-container {
				position: relative;
				display: flex;
				align-items: center;

				.job {
					margin-right: 30rpx;
					font-size: 30rpx;
					font-weight: 700;
					color: #666;
				}

				.arrow {
					width: 40rpx;
					height: 40rpx;
				}

				.dropdown-menu {
					position: absolute;
					top: 70rpx;
					right: 0;
					background-color: #fff;
					border: 1px solid #ddd;
					border-radius: 4px;
					box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
					z-index: 40;

					.menu-item {
						padding: 20px;
						font-size: $font-size-base;
						color: #333;
					}

					.top {
						border-bottom: 1rpx solid #eee;
					}
				}
			}
		}

		.expand-menu {
			@include fixed-position(40);
			right: 65rpx;
			bottom: 200rpx;
			display: flex;
			flex-direction: row;
			justify-content: flex-end;
			border-radius: 60rpx;
			overflow: hidden;
			background: rgba(0, 0, 0, 0.3);

			image {
				box-sizing: border-box;
				width: 80rpx;
				height: 80rpx;
				padding: 10rpx;
				border: 2px solid rgba(255, 255, 255, 0.1);
				border-radius: 50rpx;
				margin: 20rpx;
			}
		}

		.scroll {
			flex: 1;
			box-sizing: border-box;
			width: 100%;
			height: 100%;
			padding-bottom: 20rpx;

			.list {
				height: 100%;
			}
		}

		.popup-content {
			background-color: #fff;
			border-radius: 8px;
			width: 80vw;

			.popup-title {
				font-size: 36rpx;
				font-weight: 500;
				text-align: center;
				margin-bottom: $spacing-base;
				background-color: #fff;
				color: #666;
				line-height: 98rpx;
				border-radius: 20rpx 20rpx 0 0;
				border: 1rpx solid #ddd;
			}

			.form-item {
				margin-bottom: 60rpx;
				padding: 0 40rpx;

				text {
					display: block;
					font-size: 30rpx;
					font-weight: 600;
					margin-bottom: 10px;
				}

				.password-input {
					width: 80%;
					height: 30px;
					padding: 0 10px;
					border: 1px solid #ddd;
					border-radius: 10rpx;
				}

				.active {
					border-color: #007AFF;
					box-shadow: 0 0 5px rgba(0, 122, 255, 0.3);
					outline: none;
				}
			}

			.selectedPlace-form {
				display: flex;
				flex-direction: row;
				align-items: baseline;
				padding: 40rpx 20rpx;
				margin: 0 20rpx;
				// margin-top: 60rpx;
				background-color: #fff;
				border-radius: 20rpx 20rpx 0 0;

				input {
					width: 50px;
					height: 30px;
					padding: 0 10rpx;
					text-align: center;
					border: 1px solid #ddd;
					border-radius: 10rpx;
					box-shadow: 0 0 3px rgba(0, 0, 0, 0.1);
					background-color: #f8f8f8;

				}
			}

			.selectedPlace {
				display: flex;
				flex-direction: row;
				flex-wrap: wrap;
				gap: 45rpx 30rpx;
				padding: 40rpx 20rpx;
				margin: 0 20rpx;
				margin-bottom: 30rpx;
				background-color: #fff;
				border-radius: 0 0 20rpx 20rpx;

				text {
					min-width: 50rpx;
					height: 50rpx;
					border-radius: 10rpx;
					background-color: #f8f8f8;
					text-align: center;
					line-height: 50rpx;
					box-shadow: 0 0 3px rgba(0, 0, 0, 0.1);
					border: 1rpx solid #ddd;
					box-sizing: border-box;

				}

				.active {
					background-color: $primary-color !important;
					color: #fff;
					border: 1rpx solid $primary-color;
				}
			}

			.popup-buttons {
				background-color: #fff;
				display: flex;
				justify-content: center;
				box-sizing: border-box;
				margin-top: 25px;
				padding: 20rpx;
				box-shadow: 0 -2rpx 4rpx rgba(0, 0, 0, 0.2);
				border-radius: 0 0 20rpx 20rpx;


				button {
					// 	width: 90px;
					// 	margin: 0 10px;
				}

				.btn-cancel {
					width: 45%;
					background-color: #f8f8f8;
					box-sizing: border-box;
					border: 1rpx solid #ddd;
					color: #333;
					border-radius: 50rpx;
				}

				.btn-confirm {
					width: 45%;
					background-color: $primary-color;
					color: #fff;
					border-radius: 50rpx;
				}
			}
		}
	}
</style>